<?php
namespace app\lib\redis;
use think\Config;
/**
 * redis同步操作类
 */
class Predis
{
	private static $smsPre = 'sms_';
	private static $userPre = 'user_';
	public $reids = null;
	private static $_stance = null;

	private function __construct(){

		$this->redis = new \Redis();
		$result = $this->redis->connect(Config::get('redis.host'),Config::get('redis.port'),Config::get('redis.timeOut'));
		if($result == false){
			throw new \Exception('connect redis error');
		}
	}

	//单例模式实例化redis
	public static function instance(){

		if(is_null(self::$_stance)){
			self::$_stance = new self;
		}
		return self::$_stance;
	}

	//设置key值
	public function set($key,$value,$expire = 0){

		if(!$key){
			return;
		}

		if(is_array($value)){
			$value = json_encode($value);
		}

		if(!$expire){
			return $this->redis->set($key,$value);
		}

		return $this->redis->setex($key,$expire,$value);
	}

	//取key值
	public function get($key){
		if(!$key){
			return '';
		}
		return $this->redis->get($key);
	}

	//获取带短信前缀的key
	public static function smsKey($key){
		return self::$smsPre.$key;
	}

	//获取带用户前缀的key
	public static function userKey($key){
		return self::$userPre.$key;
	}

	//向集合中添加元素
	public function sAdd($collection,$fd){
		return $this->redis->sAdd($collection,$fd);
	}

	//从集合中删除元素
	public function sRem($collection,$fd){
		return $this->redis->sRem($collection,$fd);
	}

	//删除指定集合中的所有元素
	public function sRemAll($collection){
		$members = $this->redis->sMembers($collection);
		foreach ($members as $k => $val) {
			$this->reis->sRem($collection,$val);
		}
	}

	//获取集合中的所有元素
	public function sMembers($collections){
		return $this->redis->sMembers($collections);
	}

	//调用方法不存在则执行该函数
	public function __call($method,$arguments){
		return '';
		// return $this->redis->$method($arguments);
	}
	
}